import axios, { AxiosInstance } from 'axios'
import { removeToken, getToken } from './token'
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 50000
})

request.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken()
    if (config.method?.toLocaleLowerCase?.() === 'get') {
      config.params = { ...config.data }
      delete config.data
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 401) {
      removeToken()
      window.location.reload()
    }
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

export default request
